import { BASE_URL } from '../../common/config';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tempFilePath:'',
    bookName:'',//书名
    bookId:"",
    BookText:'',
    chapters:[],
    nowChapter:0,//当前章节
    maxChapter:0,//总章节
    scrollTop:0,//设置初始滑动位置
    nowScrollTop:0,//获取上次滑动位置
    show: false,//目录弹出层
    showNote:false,//笔记弹出层
    nowProgress:0,//保存记录当前滑动位置
    noteText:"",//笔记内容
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let bookId=options.bookid
    let bookName=options.bookname
    this.setData({
      bookId:bookId
    })
    wx.setNavigationBarTitle({
      title: bookName
    })
    this.getBookFileUrl(bookId)
    // console.log("分割后的数组:",this.parseChapters(this.data.BookText));
    setTimeout(()=>
    {
      this.setData({
      scrollTop:this.data.nowScrollTop
    })
    }, 100)
    this.getProgress()
    this.getNote()
  },
  getBookFileUrl(bookId){
    wx.request({
      url: `${BASE_URL}/BookFileUrl`,
      method:'GET',
      data:{
        bookId:bookId
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success:(res)=>{
        // console.log(res)
        let FileUrl=res.data.data
        this.getBookText(FileUrl,bookId)
      },
      fail:(err)=>{}
    })
  },
  getBookText(FileUrl,bookId){
    // 将文件保存到本地文件系统
        const fs = wx.getFileSystemManager();
        const savedFilePath = wx.env.USER_DATA_PATH +"/"+bookId+ '.txt';
        wx.getFileSystemManager().stat({
          path: savedFilePath,
          success:(res)=> {
            console.log('文件已存在:', res);
            // 文件已存在，直接读取
            fs.readFile({
              filePath: savedFilePath,
              encoding: 'utf8',
              success: (readRes) => {
                // console.log('文件内容：', readRes);
                let BookText=readRes.data
                let chapters=this.parseChapters(BookText)
                console.log("分割后的数组:",chapters);
                this.setData({
                  BookText:BookText,
                  chapters:chapters,
                  maxChapter:chapters.length,
                })
              },
              fail: (readError) => {
                console.error('读取文件失败：', readError);
              }
            });
          },fail:()=> {
            wx.downloadFile({
              // url: 'https://changqing1145.oss-cn-beijing.aliyuncs.com/%E6%B4%BB%E7%9D%80.txt',
              url:FileUrl,
              success: (res) => {
                // console.log(res);
                const tempFilePath = res.tempFilePath;
                this.setData({
                  tempFilePath: tempFilePath
                });
                fs.saveFile({
                  tempFilePath: tempFilePath,
                  filePath: savedFilePath,
                  success: (saveRes) => {
                    console.log('文件保存成功：', saveRes);
                    // 读取已保存的文件
                    fs.readFile({
                      filePath: saveRes.savedFilePath,
                      encoding: 'utf8',
                      success: (readRes) => {
                        // console.log('文件内容：', readRes);
                    let BookText=readRes.data
                        let chapters=this.parseChapters(BookText)
                        console.log("分割后的数组:",chapters);
                        this.setData({
                          BookText:BookText,
                          chapters:chapters,
                          maxChapter:chapters.length,
                        })
                      },
                      fail: (readError) => {
                        console.error('读取文件失败：', readError);
                      }
                    });
                  },
                  fail: (saveError) => {
                    console.error('保存文件失败：', saveError);
                  }
                });
              },
              fail: (error) => {
                console.error('下载文件失败：', error);
              }
            });
          }
        });
  },
// 支持更多章节格式
// parseChapters(content) {
//   // console.log(content)
//   const CHAPTER_REG = /(^|\n)\s*((序章|\S+前言|前言|楔子|第[零一二三四五六七八九十百千万]+章|第\d+章|Chapter\s+\d+|【.*?】)\s*.*?)(\n|$)/g;

//   let chapters = [];
//   let match;
//   // console.log(CHAPTER_REG.exec(content))
//   while ((match = CHAPTER_REG.exec(content)) != null) {
//     // console.log(match)
//     const title = match[2].trim();
//     const chapterName=match[3]
//     chapters.push({
//       title: title,
//       chapterName:chapterName,
//     });
//   }
//   return chapters;
// },
parseChapters(content) {
  // 优化正则表达式，精确匹配章节标题
  const CHAPTER_REG = /(第[零一二三四五六七八九十百千万]+章)/g;

  let chapters = [];
  let lastIndex = 0;
  let match;
  
  // 第一阶段：定位所有章节标题
  while ((match = CHAPTER_REG.exec(content)) !== null) {
    console.log(match)
    // 如果标题出现在文本中间（非开头位置）
    if (match.index > 0 && !/^\s/.test(content[match.index - 1])) {
      continue;
    }

    const title = match[1];
    const titleEnd = match.index + title.length;

    // 跳过已经处理过的内容
    if (match.index < lastIndex) continue;

    // 设置前一章节的结束位置
    if (chapters.length > 0) {
      chapters[chapters.length - 1].end = match.index;
    }

    chapters.push({
      title: title,
      start: match.index,
      end: content.length
    });

    lastIndex = titleEnd;
  }

  // 处理最后一个章节的结束位置
  if (chapters.length > 0) {
    chapters[chapters.length - 1].end = content.length;
  }

  // 第二阶段：提取纯净内容
  chapters = chapters.map((chap, index) => {
    let contentStart = chap.start + chap.title.length;
    let contentEnd = chap.end;

    // 处理紧接标题后的内容
    if (index < chapters.length - 1) {
      contentEnd = chapters[index + 1].start;
    }

    // 提取内容并清理空白
    const chapterContent = content.slice(contentStart, contentEnd)
      .replace(/^\s+/, '') // 去除开头空白
      .replace(/\s+$/, ''); // 去除结尾空白

    return {
      ...chap,
      content: chapterContent
    };
  });

  return chapters;
},
lastChapter() {
  this.setData({
    nowChapter: this.data.nowChapter - 1,
    scrollTop:0
  // }, () => {
  //   // 切换章节后，滚动到页面顶部
  //   wx.pageScrollTo({
  //     scrollTop: 0,  // 设置滚动到顶部
  //     duration: 0  // 可选，动画时长（单位：ms）
  //   });
  });
},
nextChapter(){
  this.setData({
    nowChapter:this.data.nowChapter+1,
    scrollTop:0
  // }, () => {
  //   wx.pageScrollTo({
  //     scrollTop: 0,
  //     duration: 0
  //   });
  });
},
onScroll(e) {
  if(e.detail.scrollTop-this.data.nowProgress>=40||e.detail.scrollTop-this.data.nowProgress<=-40){
  this.setData({
    nowProgress: Math.ceil(e.detail.scrollTop)
  });
  // console.log(this.data.nowProgress)
}
},
showPopup() {
  this.setData({ show: true });
},
note() {
  this.setData({ showNote: true });
},
changeChapter(e){
  let chapterindex=e.currentTarget.dataset.chapterindex
  this.setData({
    nowChapter:chapterindex,
    scrollTop:0
  })
},
onClose() {
      this.setData({ show: false });
},
onNote() {
      this.setData({ showNote: false });
},
saveProgress(){
  let openid=wx.getStorageSync('openid')
  let bookId=this.data.bookId
  let nowProgress=this.data.nowProgress
  let nowChapter=this.data.nowChapter
  wx.request({
    url: `${BASE_URL}/saveProgress`,
    method:'POST',
    data:{
      bookId:bookId,
      openId:openid,
      nowPage:nowChapter,
      pageProgress:nowProgress,
    },
    success:(res)=>{
      // console.log(res)
    },
    fail:(err)=>{}
  })
},
getProgress(){
  let openid=wx.getStorageSync('openid')
  let bookId=this.data.bookId
  wx.request({
    url: `${BASE_URL}/getProgress`,
    method:'POST',
    data:{
      bookId:bookId,
      openId:openid
    },
    success:(res)=>{
      // console.log(res)
      this.setData({
        nowChapter:res.data.now_page==null?0:res.data.now_page,
        nowScrollTop:res.data.page_progress==null?0:res.data.page_progress
      })
    },
    fail:(err)=>{}
  })
},
getInput(e){
  this.setData({
    noteText:e.detail.value
  })
},
saveNote(){
  // console.log(this.data.noteText)
  let openid=wx.getStorageSync('openid')
  let bookId=this.data.bookId
  let noteText=this.data.noteText
  wx.request({
    url: `${BASE_URL}/saveNote`,
    method:'POST',
    data:{
      bookId:bookId,
      openId:openid,
      noteText:noteText
    },
    success:(res)=>{
      console.log(res)
    },
    fail:(err)=>{}
  })
  this.onNote()
},
getNote(){
  // console.log(this.data.noteText)
  let openid=wx.getStorageSync('openid')
  let bookId=this.data.bookId
  let noteText=this.data.noteText
  wx.request({
    url: `${BASE_URL}/getNote`,
    method:'POST',
    data:{
      bookId:bookId,
      openId:openid
    },
    success:(res)=>{
      // console.log(res)
      this.setData({
        noteText:res.data
      })
    },
    fail:(err)=>{}
  })
},
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    this.saveProgress()
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    this.saveProgress()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})